﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace XiaLastorm.Sharpshooter
{
	/// <summary>
	/// 服务器与客户端之间传递的信息
	/// </summary>
	[Serializable]
	public abstract class Message
	{
		/// <summary>
		/// 转换为字节数组
		/// </summary>
		/// <returns>
		/// 字节数组
		/// </returns>
		public byte[] ToBytes()
		{
			BinaryFormatter formatter = new BinaryFormatter();
			using (MemoryStream stream = new MemoryStream())
			{
				formatter.Serialize(stream, this);
				stream.Seek(0, SeekOrigin.Begin);
				return stream.GetBuffer();
			}
		}

		/// <summary>
		/// 从字节数组生成<see cref="Message"/>的新实例
		/// </summary>
		/// <param name="bytes">字节数组</param>
		/// <returns>
		///   <see cref="Message"/>的新实例
		/// </returns>
		public static Message FromBytes(byte[] bytes)
		{
			try
			{
				BinaryFormatter formatter = new BinaryFormatter();
				using (MemoryStream stream = new MemoryStream(bytes))
				{
					return formatter.Deserialize(stream) as Message;
				}
			}
			catch
			{
				return null;
			}
		}
	}
}
